package com.itfreer.data.check.imp;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.data.check.ICheck;
import com.itfreer.form.api.dictionary.DictionaryEntity;
import com.itfreer.form.api.dictionary.DictionaryService;
import com.itfreer.utils.json.JsonUtils;

/**
 * 域值检查 基于域值的显示值
 */
@Component("DictionaryTextCheck")
public class DictionaryTextCheck implements ICheck {

	@Autowired
	private DictionaryService dictionaryService;

	/**
	 * 定义进行检查标准类
	 * 
	 * @param entity
	 *            object对象
	 * @param paraString
	 *            {field:dicname} 字段名:字典名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String runCheck(Object entity, String paraString) {
		// 数据只支持Map对象，当前
		if (!(entity instanceof Map)) {
			return "只支持Map类型的检查数据格式";
		}
		Map<String, Object> data = (Map<String, Object>) entity;
		if (data == null || data.size() <= 0) {
			return null;
		}
		if (paraString == null || paraString.equals("")) {
			return null;
		}

		List<DictionaryCheckPara> paras = (List<DictionaryCheckPara>) JsonUtils.toBean(paraString,
				JsonUtils.getCollectionType(List.class, DictionaryCheckPara.class));
		if (paras == null || paras.size() <= 0) {
			return "检查参数转换失败";
		}

		for (DictionaryCheckPara para : paras) {
			if (!data.containsKey(para.getFieldName())) {
				return "配置的字段【" + para.getFieldAliasName() + "】在数据中不存在";
			}
			Object value = data.get(para.getFieldName());
			if (value == null || value.toString().equals("")) {
				continue;
			}
//			List<DictionaryEntity> items = dictionaryService.getAll(para.getFieldDicname());
			List<DictionaryEntity> items = dictionaryService.getAllList(para.getFieldDicname(), null, null);
			if (items == null) {
				return "字段【" + para.getFieldAliasName() + "】中配置的字典【" + para.getFieldDicname() + "】无法找到";
			}

			String textValue = value.toString().trim();
			Boolean find = false;
			for (DictionaryEntity item : items) {
				if (item.getDisplay().equals(textValue)) {
					find = true;
					break;
				}
			}
			if (!find) {
				return "字段【" + para.getFieldAliasName() + "】值【" + textValue + "】在字典" + para.getFieldDicname() + "中无法找到";
			}
		}

		return null;
	}
}